package com.tyl.xtk.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tyl.xtk.beans.po.Permission;
import com.tyl.xtk.beans.query.PageQuery;
import com.tyl.xtk.beans.vo.PageResult;
import com.tyl.xtk.beans.vo.Result;
import com.tyl.xtk.config.validation.groups.Insert;
import com.tyl.xtk.config.validation.groups.Update;
import com.tyl.xtk.service.PermissionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.groups.Default;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 权限管理控制器
 */
@RestController
@RequestMapping("permission")
@Tag(name = "权限管理")
public class PermissionController {

    @Resource
    PermissionService permissionService;

    @GetMapping("")
    @Operation(summary = "获取权限列表（分页）")
    public PageResult<Permission> page(PageQuery pageQuery) {
        IPage<Permission> permissionPage = permissionService.selectPage(pageQuery.toPage());
        return PageResult.success(permissionPage);
    }

    @GetMapping("{id}")
    @Operation(summary = "获取权限详情")
    public Result<Permission> one(@PathVariable @NotNull Long id) {
        Permission permission = permissionService.selectById(id);
        if (permission == null) {
            return Result.fail("权限不存在");
        }
        return Result.success(permission);
    }

    @PostMapping("")
    @Operation(summary = "创建权限")
    public Result<Permission> post(@RequestBody @Validated({Insert.class, Default.class}) Permission permission) {
        boolean insert = permissionService.insert(permission);
        if (!insert) {
            return Result.fail("创建权限失败");
        }
        return Result.success(permission);
    }

    @PutMapping("")
    @Operation(summary = "更新权限")
    public Result<Permission> put(@RequestBody @Validated({Update.class, Default.class}) Permission permission) {
        boolean update = permissionService.update(permission);
        if (!update) {
            return Result.fail("更新权限失败");
        }
        return Result.success(permission);
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除权限")
    public Result<String> delete(@PathVariable @NotNull Long id) {
        boolean remove = permissionService.removeById(id);
        if (!remove) {
            return Result.fail("删除权限失败");
        }
        return Result.success("删除权限成功");
    }
}